import os
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from config import ELEMENT_LOAD_TIMEOUT, DOWNLOAD_DIR

def wait_for_element(driver, by, element, timeout=ELEMENT_LOAD_TIMEOUT):
    """
    Waits for an element to be loaded on the page.

    :param driver: The WebDriver instance.
    :param by: By strategy to locate the element.
    :param element: The locator of the element to find.
    :param timeout: Maximum time to wait for the element.
    :return: The found element.
    """
    return WebDriverWait(driver, timeout).until(EC.presence_of_element_located((by, element)))

def enter_text(driver, text):
    """
    Enters the given text into the text area on the website.

    :param driver: The WebDriver instance.
    :param text: The text to enter.
    """
    text_area = wait_for_element(driver, By.TAG_NAME, "textarea")
    text_area.clear()
    text_area.send_keys(text)

def click_download_button(driver):
    """
    Clicks the download button on the website to initiate the audio file download.

    :param driver: The WebDriver instance.
    """
    download_button = wait_for_element(driver, By.XPATH, "//button[contains(text(),'下载')]")
    download_button.click()

def wait_for_download_to_complete():
    """
    Waits for the download to complete by checking the download directory for a new file.

    :return: The path to the downloaded file.
    """
    initial_files = os.listdir(DOWNLOAD_DIR)
    while True:
        time.sleep(1)  # Check every second
        current_files = os.listdir(DOWNLOAD_DIR)
        new_files = [f for f in current_files if f not in initial_files]
        if new_files:
            return os.path.join(DOWNLOAD_DIR, new_files[0])
